<?php
declare (strict_types = 1);

namespace app\auth\controller;

use app\auth\BaseController;
use app\auth\common\util\ApiUtil;
use app\auth\model\RightModel;
use app\auth\service\RightService;
use think\facade\Db;
use think\facade\Validate;

class RightController extends BaseController
{

    public function __construct(RightService $rightService)
    {
        $this->rightService = $rightService;
    }

    public function list()
    {
        $params = request()->param();
        $where = $limit = $whereIn = array();
        $limit['page'] = !empty($params['page'])?intval($params['page']):1;
        $limit['pagesize'] = !empty($params['pagesize'])?intval($params['pagesize']):10;
        $name = $params['name']??null;
        if(!empty($name)) $where[] = ['name','=', $name];
        $p_name = $params['p_name']??null;
        if(!empty($p_name)){ //从父级搜索菜单
            $p_list = RightModel::field('id','pid')
                ->where('pid', RightModel::PID_BASE)
                ->where('name', 'like', '%'.$params['p_name'].'%')
                ->select();
            $p_ids = $p_list->column('id');
            $whereIn = ['pid',$p_ids];
        }
        $type = $params['type']??null;
        if(!empty($type)) $where[] = ['type', '=',$type];
        $pid_type = $params['pid_type']??-1; //菜单层级
        if ($pid_type == 0) $where[] = ['pid', '=',0];
        if ($pid_type == 1) $where[] = ['pid', '>',0];
        $total = $this->rightService->count($where,$whereIn);
        $list = $this->rightService->list($where , $limit,[],$whereIn);
        return ApiUtil::normal(['total'=>$total,'list'=>$list]);
    }

    public function add()
    {
        $params = request()->param();
        $model = $this->rightService->model();
        $validate = Validate::rule([
            'name'=>'require|unique:'.$model->getTable(),
            'pid' => 'require',
            'value' => 'require',
            'type' => 'require',
            'status' => 'require',
        ]);
        if(!$validate->check($params)) return ApiUtil::normal(null, $validate->getError(), ApiUtil::CODE_FAIL);
        //数据库数据校验
        if ($params['pid'] != $model::PID_BASE){
            if(!$this->rightService->count(['id'=>$params['pid'],'pid'=>$model::PID_BASE])) return ApiUtil::normal(null, '父级权限不存在', ApiUtil::CODE_FAIL);
        }
        $data = array();
        $data['name'] = $params['name'];
        $data['pid'] = $params['pid'];
        $data['url'] = $params['url']??null;
        $data['type'] = $params['type'];
        $data['value'] = $params['value']??null;
        $data['status'] = $params['status'];
        $data['sort'] = 0;
        $data['createtime'] = time();
        $lastId = $this->rightService->insertGetId($data);
        if(empty($lastId)) return ApiUtil::normal(null, '创建权限失败', ApiUtil::CODE_FAIL);
        return ApiUtil::normal(['id'=>$lastId]);
    }

    public function update(){
        $id = input('id', null);
        if(empty($id)) return ApiUtil::normal(null, '请输入权限ID', ApiUtil::CODE_FAIL);
        $name = input('name', null);
        $pid = input('pid', -1);
        $url = input('url', '');
        $value = input('value', '');
        $type = input('type', null);
        $status = input('status', null);
        $model = $this->rightService->model();
        DB::startTrans();
        try{
            if ($pid != -1 && $pid != $model::PID_BASE){
                !$this->rightService->count([['id','=',$pid],['pid','=',$model::PID_BASE]]) && ApiUtil::abort('父级权限不存在');
            }
            if(!empty($name)) $this->rightService->count(['name'=>$name],['id',[$id]]) && ApiUtil::abort('已存在权限名称');
            $data = array();
            if(!empty($name)) $data['name'] = $name;
            if(!empty($url)) $data['url'] = $url;
            if(!empty($type)) $data['type'] = $type;
            if(!empty($value)) $data['value'] = $value;
            if(!empty($value)) $data['status'] = $status;
            $update = $this->rightService->update(['id'=>$id],$data);
            if(!$update) ApiUtil::abort('修改权限失败');
            DB::commit();
            return ApiUtil::normal( ['id'=>$id]);
        }catch (\Exception $e){
            DB::rollBack();
            return ApiUtil::excep($e);
        }
    }

    public function delete(){
        $ids = input('ids',[]);
        if (empty($ids)) return ApiUtil::normal(null, "请传入要删除的权限ID", ApiUtil::CODE_FAIL);
        DB::startTrans();
        try{
            $this->rightService->delete(['pid',$ids]);
            $del = $this->rightService->delete(['id',$ids]);
            if(!$del) ApiUtil::abort( "删除失败");
            DB::commit();
            return ApiUtil::normal(['id'=>$ids]);
        }catch (\Exception $e){
            DB::rollBack();
            return ApiUtil::excep($e);
        }
    }

    // 筛选配置
    public function opt(){
        $model = $this->rightService->model();
        //父级权限
        $pright_list = $this->rightService->list(['pid'=>$model::PID_BASE]);
        $pright_list[] = ['id'=>0,'name'=>'无父级'];
        return ApiUtil::normal([
            'pright_list' => $pright_list,
            'status_obj' => $model::$STATUS_STR,
            'type_obj' => $model::$TYPE_STR,
        ]);
    }
}
